<?php
namespace app\api\service;

use app\api\controller\Base;
use app\api\model\Order as OrderModel;
use app\api\model\Product as ProductModel;
use app\api\service\OrderService;
use app\common\enum\OrderEnum;
use app\common\enum\ProductEnum;
use think\Db;
use think\Exception;
use think\Log;
use think\Request;

class DeviceService extends Base
{

    // 主动更新订单核销二维码
    public function qrCodeUpdate()
    {
        $request = Request::instance()->get();
        parent::validate($request, 'QrCodeValidate');
        $domain = Request::instance()->domain();
        $order = (new OrderModel())->where('id', '=', $request['order_id'])->find();
        $product_snapshot = json_decode($order['product_snapshot'], true);
        $res = (new OrderModel())->where('id', $order['id'])->update(['qr_number' => self::cancelNumber($order['product_id'])]);
        $order = (new OrderModel())->where('id', '=', $order['id'])->find();
        return [
            'qr_code' => $domain . $order['qr_code'], //二维码图片
            'qr_code_encrypt' => self::lock_url($order['qr_number'],'password'), //new加密参数用于生成二维码
            'rescue_code' => $order['id'].substr($order['order_number'],-4), //new 救援编号 订单id+订单编号
            'qr_number' => $order['qr_number'], //核销编号
            'name' => $product_snapshot['name'], //名称
            'image' => $product_snapshot['image'], //图片
            'status' => $order['status'] //当前二维码状态
        ];
    }

    // 扫码核销
    public function cancellation($qr_code)
    {
        $order = (new OrderModel())->where('qr_number', '=', $qr_code)->find(); //当前核销码所对应的订单
        $userId = $order['user_id'];
        Log::info('查询订单：' . $order);
        if ($qr_code != $order['qr_number']) {
            $this->error('该二维码不存在');
            Log::info('该二维码不存在');
        }
        if ($order['status'] == OrderEnum::ORDER_WRITTEN) { //如果当前状态是待核销状态 则是入场
            (new OrderService())->approach($userId, $order); //入场核销
        } else if ($order['status'] == OrderEnum::ORDER_SERVICE) { //如果当前状态是使用中，则是出场
            (new OrderService())->appear($userId, $order, $qr_code); //出场核销
        }
    }


}
